import 'dart:convert';

import 'package:eplorex/pages/root_page.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

import '../../providers/local_shared_cache.dart';
import '../../providers/user_context.dart';
import '../../utils/HttpUtil.dart';

class LoginPage extends StatefulWidget {
  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  final _formKey = GlobalKey<FormState>();
  bool _obscureText = true;
  String _username = '';
  String _password = '';

  void _login() {
    if (_formKey.currentState!.validate()) {
      _formKey.currentState!.save();
      HttpUtil.getInstance()
          .post('/api/user/login',
              data: jsonEncode({'phone': _username, 'password': _password}))
          .then((value) {
        var setCookie = value?.headers['authorization'];
        if (setCookie != null) {
          LocalSharedCache.saveString("authorization", jsonEncode(setCookie));
        }
        if (value!.data['data'] != null) {
          LocalSharedCache.saveString(
              "loginUid", jsonEncode(value!.data['data']));
          UserContext.fromJson(value!.data['data']);
        }
        Navigator.pushAndRemoveUntil(context,
            MaterialPageRoute(builder: (context) => HomePage()), (_) => false);
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: BackButton(),
        title: Text(
          '登录',
          style: TextStyle(color: Colors.blue),
        ),
      ),
      body: Container(
        padding: const EdgeInsets.all(20.0),
        child: Column(
          children: [
            Form(
              key: _formKey,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Container(
                    margin: EdgeInsets.only(bottom: 10),
                    child: Text(
                      "手机号/用户名登录",
                      style: TextStyle(fontSize: 20),
                    ),
                  ),
                  TextFormField(
                    decoration: InputDecoration(
                      filled: true,
                      fillColor: Colors.blue.shade100,
                      hintText: '用户名',
                      border: OutlineInputBorder(
                        gapPadding: 0,
                        borderSide: BorderSide(
                          color: Colors.blue.shade100,
                        ),
                        borderRadius: BorderRadius.all(Radius.circular(10)),
                      ),
                    ),
                    validator: (value) {
                      if (value == null || value.isEmpty) {
                        return '请输入用户名';
                      }
                      return null;
                    },
                    onSaved: (value) => _username = value!,
                  ),
                  const SizedBox(
                    height: 20,
                  ),
                  Container(
                    margin: EdgeInsets.only(bottom: 10),
                    child: Text(
                      "密码",
                      style: TextStyle(fontSize: 20),
                    ),
                  ),
                  TextFormField(
                    obscureText: _obscureText,
                    decoration: InputDecoration(
                      filled: true,
                      fillColor: Colors.blue.shade100,
                      hintText: '密码',
                      suffixIcon: IconButton(
                        icon: Icon(_obscureText
                            ? Icons.visibility
                            : Icons.visibility_off),
                        onPressed: () {
                          setState(() {
                            _obscureText = !_obscureText;
                          });
                        },
                      ),
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.all(Radius.circular(10)),
                      ),
                    ),
                    validator: (value) {
                      if (value == null || value.isEmpty) {
                        return '请输入密码';
                      }
                      return null;
                    },
                    onSaved: (value) => _password = value!,
                  ),
                ],
              ),
            ),
            Container(
              alignment: Alignment.centerRight,
              child: TextButton(
                  onPressed: () {},
                  child: Text(
                    '忘记密码?',
                    style: TextStyle(color: Colors.blue),
                  )),
            ),
            const SizedBox(
              height: 10,
            ),
            SizedBox(
              width: MediaQuery.of(context).size.width*0.75,
              child: FilledButton(
                onPressed: () {
                  _login();
                },
                child: const Text('登录'),
                style: FilledButton.styleFrom(
                  foregroundColor: Colors.white,
                  backgroundColor: Colors.blue,
                ),
              ),
            ),
            const Padding(padding: EdgeInsets.only(top: 20),child: Text('其他登录方式'),),
            Wrap(
              children: [
                IconButton(
                    onPressed: () {},
                    icon: Icon(
                      Icons.access_time,
                      size: 40,
                    )),
                IconButton(
                    onPressed: () {},
                    icon: Icon(
                      Icons.access_time,
                      size: 40,
                    )),
                IconButton(
                    onPressed: () {},
                    icon: Icon(
                      Icons.access_time,
                      size: 40,
                    )),
              ],
            )
          ],
        ),
      ),
    );
  }
}
